<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue';
import { onLoad, onPageScroll } from '@dcloudio/uni-app';
import { throttle } from 'lodash-es';

import { getHotelDetails, getHotelRoomsList } from '@/api/hotels';
import { createPreorder } from '@/api/orders';
import { RouteMap, useRouter } from '@/router';
import { useCheckoutStore } from '@/store/checkout';
import { usePopupStore } from '@/store/popup';

import DetailsBaseInfo from './components/details-base-info.vue';
import DetailsRooms from './components/details-rooms.vue';
import DetailsRoomDetails from './components/details-room-details.vue';
import { addCollect, delCollect } from '@/api/user';
import { useAuthStore } from '@/store/auth';
import { useLocale } from '@/locale/locale';
import { isWechat } from '@/utils/platform';
import { useTitle } from '@/hooks/useTitle';

const { t } = useLocale();
const router = useRouter();
const checkoutStore = useCheckoutStore();
const popupStore = usePopupStore();
const authStore = useAuthStore();

onMounted(() => {
  popupStore.init();
});

const data = ref({
  id: 0,
  collectId: 0,
  puid: '0',
  info: [],
  name: '',
  description: '',
  tagsList: [],
  address: '',
  rooms: [],
  busStation: '',
  subway: '',
  checkInGuide: '',
  cancellationPolicy: '',
  latitude: 0,
  longitude: 0
});

const current = ref(0);
const currentRoom = ref({ uid: '', id: '', occupancy: 9999 });
const roomDetailsRef = ref();

function handleSwiperChange(e: any) {
  current.value = e.detail.current;
}

function openPopup(
  type: 'DatePicker' | 'GuestNumberPicker' | 'RoomDetails',
  uid?: string,
  id?: string,
  occupancy?: number
) {
  if (type === 'DatePicker') {
    popupStore.openDatePicker();
  } else if (type === 'GuestNumberPicker') {
    currentRoom.value.uid = uid as string;
    currentRoom.value.id = id as string;
    currentRoom.value.occupancy = occupancy as number;
    nextTick(() => {
      if (checkoutStore.mode === 1) {
        popupStore.openGuestNumberPicker();
      } else {
        popupStore.openBookersNumberPicker();
      }
    });
  } else {
    roomDetailsRef.value?.open(uid, id);
  }
}

async function handleDatePickerChange(startDate?: string, endDate?: string) {
  checkoutStore.setDate(startDate, endDate);
  const res = await getHotelRoomsList({
    puid: data.value.puid,
    startDate: checkoutStore.startDate,
    endDate: checkoutStore.endDate,
    roomNumber: checkoutStore.roomsNumber.toString(),
    bookerNumber: checkoutStore.bookersNumber.toString()
  });
  data.value.rooms = res.data.property ?? [];
  popupStore.closeDatePicker();
}

async function handleGuestNumberPickerChange(
  adultsNumber: number,
  childrenNumber: number,
  babysNumber: number
) {
  checkoutStore.setBookersNumber(adultsNumber, childrenNumber, babysNumber);
  if (!authStore.isLoggedIn) {
    uni.navigateTo({
      url: '/pages/auth/login'
    });
    return false;
  }
  const room: any = data.value.rooms.find((item: any) => item.uid === currentRoom.value.uid);
  const res = await createPreorder({
    puid: data.value.puid,
    checkin_at: checkoutStore.startDate,
    checkout_at: checkoutStore.endDate,
    roomItems: [
      {
        room_id: room.uid,
        roomNum: 1,
        adult: checkoutStore.adultsNumber,
        child: checkoutStore.childrenNumber,
        infant: checkoutStore.babysNumber
      }
    ],
    isLease: checkoutStore.mode
  });
  if (res.code === 0) {
    router.to(RouteMap.checkout, {
      preOrderSn: res.data.preOrderSn
    });
  }
}

async function delCollectSub(collectId: number) {
  const res = await delCollect(collectId);
  uni.showToast({
    title:
      res.code == 0 ? t('LHTKey_collectionCancelSuccess') : t('LHTKey_collectionCancelFailure'),
    icon: 'none'
  });
  if (res.code == 0) {
    data.value.collectId = 0;
  }
}

async function addCollectSub(id: number) {
  if (!authStore.isLoggedIn) {
    uni.navigateTo({
      url: '/pages/auth/login'
    });
    return false;
  }
  const payload: any = {
    collectId: id,
    collectType: 'HOST'
  };
  const res = await addCollect(payload);
  uni.showToast({
    title: res.code == 0 ? t('LHTKey_collectionSuccess') : t('LHTKey_collectionFailure'),
    icon: 'none'
  });
  if (res.code == 0) {
    const res1 = await getHotelDetails(id as unknown as string);
    data.value.collectId = res1.data.collectId;
  }
}

onLoad(async (options) => {
  const [r1, r2] = await Promise.all([
    getHotelDetails(options!.id),
    getHotelRoomsList({
      puid: options!.puid,
      startDate: checkoutStore.startDate,
      endDate: checkoutStore.endDate,
      roomNumber: checkoutStore.roomsNumber.toString(),
      bookerNumber: checkoutStore.bookersNumber.toString()
    })
  ]);
  data.value.id = r1.data.id;
  data.value.collectId = r1.data.collectId;
  data.value.puid = options!.puid;
  data.value.info = r1.data.galleryImages.map((item: any) => item.fileUrl);
  data.value.name = r1.data.name;
  data.value.description = r1.data.description;
  data.value.tagsList = r1.data.tagList ?? [];
  data.value.address = r1.data.address;
  data.value.rooms = r2.data.property ?? [];
  data.value.busStation = r1.data.busStation;
  data.value.subway = r1.data.subway;
  data.value.checkInGuide = r1.data.checkInGuide;
  data.value.cancellationPolicy = r1.data.cancelPolicy;
  data.value.latitude = Number(r1.data.ggLat ?? 0);
  data.value.longitude = Number(r1.data.ggLng ?? 0);
});

// 增加详情页导航栏的滚动效果
const navbarSettings = reactive({
  backgroundColor: '#ffffff00',
  color: '#fff',
  shadow: false,
  title: ''
});

const pageScrollHandler = throttle((scrollTop: number) => {
  if (scrollTop > 150) {
    navbarSettings.backgroundColor = '#ffffffff';
    navbarSettings.color = '#3d3d3d';
    navbarSettings.shadow = true;
    navbarSettings.title = data.value.name;
  } else {
    navbarSettings.backgroundColor = '#ffffff00';
    navbarSettings.color = '#fff';
    navbarSettings.shadow = false;
    navbarSettings.title = '';
  }
}, 100);

onPageScroll((e) => {
  pageScrollHandler(e.scrollTop);
});

let mapContextInstance: UniNamespace.MapContext;

const openLocation = () => {
  if (!mapContextInstance) {
    mapContextInstance = uni.createMapContext('apt-details-map');
  }
  mapContextInstance.openMapApp({
    latitude: data.value.latitude,
    longitude: data.value.longitude,
    destination: data.value.name
  });
};
</script>

<template>
  <page-meta :page-style="`overflow: ${popupStore.isHidden ? 'hidden' : 'visible'}`"></page-meta>

  <uni-nav-bar
    v-if="isWechat()"
    :background-color="navbarSettings.backgroundColor"
    :border="false"
    :color="navbarSettings.color"
    :shadow="navbarSettings.shadow"
    :title="navbarSettings.title"
    fixed
    left-icon="left"
    status-bar
    @click-left="router.back"
  />

  <view class="absolute top-0 left-0 right-0">
    <view
      v-if="authStore.isLoggedIn"
      style="
        position: absolute;
        top: 256rpx;
        right: 28rpx;
        z-index: 98;
        width: 88rpx;
        height: 88rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 16rpx;
        background: rgba(0, 0, 0, 0.5);
      "
      @click="data.collectId > 0 ? delCollectSub(data.collectId) : addCollectSub(data.id)"
    >
      <image
        :src="
          data.collectId > 0
            ? '/static/hotel_details_collect.png'
            : '/static/hotel_details_nocollect.png'
        "
        style="display: block; width: 52rpx; height: 52rpx"
      />
    </view>
    <uni-swiper-dot
      :current="current"
      :dots-styles="{
        bottom: 20,
        backgroundColor: 'rgba(255, 255, 255, 0.48)',
        border: '1px solid rgba(255, 255, 255, 0.48)',
        selectedBackgroundColor: '#fff',
        selectedBorder: '1px solid #fff'
      }"
      :info="data.info"
      mode="dot"
      style="height: 600rpx"
    >
      <swiper autoplay circular style="height: 600rpx" @change="handleSwiperChange">
        <swiper-item v-for="(item, index) in data.info" :key="index">
          <image :src="item" class="w-full h-full" />
        </swiper-item>
      </swiper>
    </uni-swiper-dot>

    <view class="relative" style="top: -16rpx">
      <details-base-info :address="data.address" :name="data.name" :tags-list="data.tagsList">
        <view class="apt-details-map" @click="openLocation">
          <image
            class="apt-details-map-bg"
            src="https://apt11-1251002327.cos.ap-tokyo.myqcloud.com/miniapp/hotel_details_map_bg.png"
          />
          <view class="apt-details-map-content flex items-center justify-between">
            <view class="apt-details-map-address">{{ data.address }}</view>
            <image class="w-5 h-5" src="/static/hotel_details_map_location.png" />
          </view>
          <map
            id="apt-details-map"
            class="absolute opacity-0"
            :latitude="data.latitude"
            :longitude="data.longitude"
          />
        </view>
      </details-base-info>

      <details-rooms
        :currency-unit="checkoutStore.currency"
        :days-number="checkoutStore.daysNumber"
        :end-date="checkoutStore.endDate"
        :items="data.rooms"
        :start-date="checkoutStore.startDate"
        @open="openPopup"
      />

      <!-- 民宿详情 -->
      <apt-section
        v-if="data.description"
        :title="t('LHTKey_homestayDetails')"
        custom-style="margin-bottom: 20rpx"
      >
        <view class="text-base text-primary leading-xl">
          {{ data.description }}
        </view>
      </apt-section>

      <!-- 出行信息 -->
      <apt-section
        v-if="data.busStation"
        :title="t('LHTKey_travelInformation')"
        custom-style="margin-bottom: 20rpx"
      >
        <view class="text-base text-primary leading-xl">{{ data.busStation }}</view>
      </apt-section>

      <!-- 入住指南 -->
      <apt-section
        v-if="data.checkInGuide"
        :title="t('LTKey_tripCheckinGuide')"
        custom-style="margin-bottom: 20rpx"
      >
        <view class="text-base text-primary leading-xl">
          {{ data.checkInGuide }}
        </view>
      </apt-section>

      <apt-booking-tips :cancellation-policy="data.cancellationPolicy"></apt-booking-tips>
    </view>
  </view>

  <!-- 弹出层 -->
  <apt-date-picker
    :end-date="checkoutStore.endDate"
    :start-date="checkoutStore.startDate"
    @update="handleDatePickerChange"
  />

  <apt-guest-number-picker
    :adults-number="checkoutStore.adultsNumber"
    :babys-number="checkoutStore.babysNumber"
    :children-number="checkoutStore.childrenNumber"
    :max-bookers-number="currentRoom.occupancy"
    @update="handleGuestNumberPickerChange"
  />

  <apt-bookers-number-picker
    :bookers-number="checkoutStore.bookersNumber"
    :max-bookers-number="currentRoom.occupancy"
    @update="handleGuestNumberPickerChange"
  />

  <details-room-details ref="roomDetailsRef"></details-room-details>
</template>

<style scoped lang="scss">
.apt-details-map {
  position: relative;
  width: 686rpx;
  height: 112rpx;

  &-bg {
    width: 100%;
    height: 100%;
  }

  &-content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: 22rpx 48rpx 22rpx 22rpx;
  }

  &-address {
    width: 458rpx;
    font-size: 24rpx;
    line-height: 34rpx;
    color: #979797;
  }
}

.absolute.opacity-0 {
  opacity: 0;
  z-index: -1;
  pointer-events: none;
  width: 100%;
  height: 100%;
}
</style>
